/*
  MinCC - Minimalist Compiler Collection
  Copyright (C) 2009 Scott Lawrence

  MinCC is free software: you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  MinCC is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  License for more details.

  You should have received a copy of the GNU General Public License
  along with mincc.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include "error.hpp"

/*
  Structure of errnos:
  0-99      miscellaneous stuff
  100-199   io errors
  200-299
  300-399
  400-499

  An errno that ends with 0 will be 'unknown' of some sort
*/
START_ERRORS()
    DECLARE_ERROR(0,"unknown")
    DECLARE_ERROR(1,"too many arguments")
    DECLARE_ERROR(2,"unkown option")
    DECLARE_ERROR(3,"too few arguments to option")

    DECLARE_ERROR(11,"not yet implemented")

    DECLARE_ERROR(101,"no such file")
    DECLARE_ERROR(102,"no such directory")
END_ERRORS

void initErrors() {
    //may someday make a hashtable of errors, to make crashing faster
}

const char *getErrorDescription(int id) {
    int i=0;
    while(errs[i].id!=-1)
        if(id==errs[i++].id) 
            return errs[--i].description;
    return "{{no such error}}";
}

void error(int line,const char *func) {
    fprintf(stderr,"Unkown error in %s at line %d\n",func,line);
}

void error(int line,const char *func,int id) {
    fprintf(stderr,"Error %d in %s at line %d: %s\n",id,func,line,getErrorDescription(id));
}

void error(int line,const char *func,int id,const char *text) {
    fprintf(stderr,"Error %d in %s at line %d: %s (\"%s\")\n",id,func,line,getErrorDescription(id),text);
}

void fatal(int line,const char *func) {
    fprintf(stderr,"Unkown fatal error in %s at line %d, aborting\n",func,line);
    exit(-1);
}

void fatal(int line,const char *func,int id) {
    fprintf(stderr,"Fatal error %d in %s at line %d: %s, aborting\n",id,func,line,getErrorDescription(id));
    exit(-1);
}

void fatal(int line,const char *func,int id,const char *text) {
    fprintf(stderr,"Fatal error %d in %s at line %d: %s (\"%s\"), aborting\n",id,func,line,getErrorDescription(id),text);
    exit(-1);
}
